﻿#include"XQHttpObject.h"
#include"XQHttpHeadRequest.h"
#include"XQHttpHeadReply.h"
#include"QCoding.h"
#include<QJsonArray>
#include<QAbstractSocket>
#include<QHostAddress>
XQHttpObject::XQHttpObject(QObject* parent)
{
	init();
}

XQHttpObject::~XQHttpObject()
{
}

QJsonDocument XQHttpObject::QVariantList_toJson(const QVariantList& list)
{
	QJsonArray jsonArray;
	for (const QVariant& variant : list) {
		jsonArray.append(QJsonValue::fromVariant(variant));
	}
	return QJsonDocument(jsonArray);
}

QString XQHttpObject::hostPort(QAbstractSocket* socket)
{
	QHostAddress ipAddress = socket->peerAddress();
	QString ip = ipAddress.toString(); // 转换为字符串形式
	// 获取已连接主机的端口号
	quint16 port = socket->peerPort();
	return QString("%1:%2").arg(ip).arg(port);
}

NetworkType XQHttpObject::serverType() const
{
	return m_serverType;
}

bool XQHttpObject::isTcpNetwork() const
{
	return m_serverType==NetworkType::Tcp;
}

bool XQHttpObject::isLocalNetwork() const
{
	return m_serverType == NetworkType::Local;
}

void XQHttpObject::setDebugModel(int model)
{
	m_debug = model;
}

void XQHttpObject::setDebugModel(Http::Debug model, bool open)
{
	if (open)
		m_debug |= model;
	else
		m_debug &= (~model);
}

void XQHttpObject::sendSignals(const QString& host, const QVariantList& data)
{
}

void XQHttpObject::addSlotFunc(const QString& name, std::function<QVariantList(const QVariantList&)> slotFunc)
{
	m_slotFunc[name] = slotFunc;
}

void XQHttpObject::removeSlotFunc(const QString& name)
{
	m_slotFunc.remove(name);
}

void XQHttpObject::clearSlotFunc()
{
	m_slotFunc.clear();
}

void XQHttpObject::init()
{
	/*addSignals("1231",this,&XQHttpObject::test);*/
}

bool XQHttpObject::ishandlingSignalsRequest(XQHttpHeadObject* header)
{
	return header->header(QNetworkRequest::ContentTypeHeader) == SignalsRequestHeader;
}

QByteArray XQHttpObject::handlingSignalsRequest(XQHttpHeadObject* header, const QByteArray& data)
{
	if (!ishandlingSignalsRequest(header))
		return QByteArray();
	XQHttpHeadReply ready;
	QVariantList  ret;
	auto name = header->header(SignalsRequestHeader);//拿到信号名字
	auto args = QJsonDocument::fromJson(data).toVariant().toList();
	emit signalsRequest(name, args);
	if (m_slotFunc.contains(name))//查找绑定的相同名字槽函数
	{
		ret = m_slotFunc[name](args);
	}
	if (!ret.isEmpty())
	{//返回数据
		ready.setHeader(QNetworkRequest::ContentTypeHeader, SignalsReplyHeader);
		ready.setHeader(SignalsReplyHeader, header->header(SignalsRequestHeader));
		ready.setContent(QVariantList_toJson(ret).toJson());
		return ready.toByteArray();
	}
	return QByteArray ();
}

bool XQHttpObject::isReadContentFinish(const XQHttpHeadObject& head, const QByteArray& data, qlonglong startIndex)
{
	if (!head.header().contains("Content-Length"))
		return true;
	auto len = head.contentLength();
	auto curSize = data.size() - startIndex;
	if (curSize >= len)
		return true;
	return false;
}

QByteArray XQHttpObject::GbkToUtf8(const QByteArray& data)
{
	return QCoding::GbkToUtf8(data);
}
